package com.ts.api.http.receive.biz;

import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.base.StringUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.common.entity.ApiParameter;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.http.receive.entity.apply.req.ApiReceiveApplyEnXin;
import com.ts.api.http.receive.entity.dataexchange.req.ApiReceiveDataExchangeEnXin;
import com.ts.api.module.api.convert.core.annotation.ApiReceive;
import com.ts.api.module.api.convert.core.annotation.ApiReceiveConvertType;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveApply;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveNotice;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.convert.receive.handler.ApiReceivePhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import java.util.Map;

/**
 * 恩信钱包&安心分期 api
 * @ Author 江小游
 * @ Date 2025/5/23 11:39
 */
@ApiReceive(apiClientId = "1962089909342588928",type = ApiReceiveConvertType.API_CHANNEL_PHONE_MD5)
public class ApiReceivePhoneMd5EnXin implements ApiReceivePhoneMd5ConvertHandler {
    private static final String KEY = "1234567890abcdef";
    private static final String IV = "fedcba0987654321";

    @Override
    public Map<String, String> requireParam(RequestVO requestVO) throws Exception {
        Assert.isNotEmptyThrows(requestVO.getBody(), new ApiMsgException(ApiEnum.API_BODY_ERROR));
        //  获取请求体参数
        Map<String, Object> map = JsonUtils.toMap(requestVO.getBody());
        String channelCode = String.valueOf(map.get("channelCode"));
        String data = String.valueOf(map.get("data"));
        //  传递什么，验证什么Key
        Assert.isNotEmptyThrows(channelCode, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("channelCode")));
        Assert.isNotEmptyThrows(data, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("data")));
        //  返回需要的数据Map
        return MapUtils.newHashMap(newMap -> {
            newMap.put("channelCode", channelCode);
            newMap.put("data", data);
        });
    }

    @Override
    public ApiReceiveDecrypt decrypt(Map<String, String> paramMap, RequestVO requestVO) throws Exception {
        String data = paramMap.get("data");
        AES aes = AES.createCbc(KEY.getBytes(), IV.getBytes());
        String decrypt = aes.decryptFromBase64Str(data);
        return new ApiReceiveDecrypt(decrypt);
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveDataExchangeEnXin parse = apiReceiveDecrypt.parse(ApiReceiveDataExchangeEnXin.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMd5DataExchange dataExchangeMessage) throws Exception {
        ApiParameter apiParameter = ApiContext.PARAMETER.get();
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();

        boolean suc = dataExchangeMessage.hasBizSuc();
        if (!suc) {
            resultMap.put("code", 500);
            resultMap.put("msg", dataExchangeMessage.getBizMsg());
            resultMap.put("data", apiParameter.get("data"));
            return resultMap;
        }

        resultMap.put("code", 10000);
        resultMap.put("msg", "操作成功");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            dataMap.put("protocolList", CollUtils.newArrayList(protocolOne -> protocolOne.add(MapUtils.newLinkedHashMap(protocol->{
                protocol.put("proto",dataExchangeMessage.getReqId());
                protocol.put("protoName","个人信息授权协议");
                protocol.put("protoUrl","https://axh.rongyiudai.com/h5ViewProtocol?uniqueCode=1fc1379861b34ef0898d7864c33b18e2");
            }))));
            dataMap.put("product", MapUtils.newLinkedHashMap(protocolMap ->{
                protocolMap.put("prodName",dataExchangeMessage.getOrgName());
                protocolMap.put("protoLogo",dataExchangeMessage.getLogoPath());
            }));
            //  价格
            dataMap.put("settleAmount", dataExchangeMessage.getPrice());
        }));
        return resultMap;
    }

    @Override
    public ApiUserRequest parseApply(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveApplyEnXin parse = apiReceiveDecrypt.parse(ApiReceiveApplyEnXin.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respApply(ApiReceiveApply applyMessage) throws Exception {
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        boolean suc = applyMessage.hasBizSuc();
        if (!suc) {
            resultMap.put("code", 300);
            resultMap.put("msg", applyMessage.getBizMsg());
            return resultMap;
        }

        resultMap.put("code", 10000);
        resultMap.put("msg", "进件成功");
        return resultMap;
    }

    @Override
    public void fieldMapping(ApiUserRequest apiUserRequest) {
        // age 年龄
        String age = apiUserRequest.getAge();
        if (!StringUtils.isEmpty(age)) {
            apiUserRequest.setAge(ApiDictUtils.convertAge(age));
        }
        // sex 性别（1男 0女）
        // sex 性别
        // 0 男
        // 1 女
        // 2 未知
        String sex = apiUserRequest.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String value = ChooseEq.create()
                    .when(sex, "1", "0")
                    .when(sex, "2", "1")
                    .end("2");
            apiUserRequest.setSex(value);
        }

        // 芝麻分 700分以上=40 650-699分=30 600-649分=20 600分以下=10 无 0
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        if (ValidParam.isNotEmpty(apiUserRequest.getSesameCredit())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getSesameCredit(), "10", "1")
                    .when(apiUserRequest.getSesameCredit(), "20", "2")
                    .when(apiUserRequest.getSesameCredit(), "30", "3")
                    .when(apiUserRequest.getSesameCredit(), "40", "4")
                    .end("1");
            apiUserRequest.setSesameCredit(value);
        }else {
            apiUserRequest.setSesameCredit("1");
        }
        // 公积金 0:无公积金，10:缴纳未满6个月，20:缴纳6个月以上
        // 公积金
        // 1.无公积金
        // 2.缴纳6个月以下
        // 3.缴纳6个月以上
        // 4.有公积金
        if (ValidParam.isNotEmpty(apiUserRequest.getProvidentFund())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getProvidentFund(), "0", "1")
                    .when(apiUserRequest.getProvidentFund(), "10", "2")
                    .when(apiUserRequest.getProvidentFund(), "20", "3")
                    .end("1");
            apiUserRequest.setProvidentFund(value);
        }else {
            apiUserRequest.setProvidentFund("1");
        }
        // 社保 0:无社保，10:缴纳未满6个月，20:缴纳6个月以上
        // 社保缴纳
        // 1-无社保
        // 2-缴纳6个月以下
        // 3-缴纳6个月以上
        // 4-有社保
        if (ValidParam.isNotEmpty(apiUserRequest.getSocialSecurity())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getSocialSecurity(), "0", "1")
                    .when(apiUserRequest.getSocialSecurity(), "10", "2")
                    .when(apiUserRequest.getSocialSecurity(), "20", "3")
                    .end("1");
            apiUserRequest.setSocialSecurity(value);
        }else {
            apiUserRequest.setSocialSecurity("1");
        }
        // 房产 0:无房产，10:有房产，不抵押，20:有房产，可抵押
        // 房产情况
        // 1-无房产
        // 2-有房不抵押
        // 3-有房可抵押
        // 4-有房产
        // 5-有按揭房产
        // 6-有全款房产
        if (ValidParam.isNotEmpty(apiUserRequest.getRealEstateInfo())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getRealEstateInfo(), "0", "1")
                    .when(apiUserRequest.getRealEstateInfo(), "10", "2")
                    .when(apiUserRequest.getRealEstateInfo(), "20", "3")
                    .end("1");
            apiUserRequest.setRealEstateInfo(value);
        }else {
            apiUserRequest.setRealEstateInfo("1");
        }
        // 车产 0:无车产，10:有车产，不抵押，20:有车产，可抵押
        // 车辆情况
        // 1.无车产
        // 2.有车不抵押
        // 3.有车可抵押
        // 4.有车
        if (ValidParam.isNotEmpty(apiUserRequest.getCarInfo())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getCarInfo(), "0", "1")
                    .when(apiUserRequest.getCarInfo(), "10", "2")
                    .when(apiUserRequest.getCarInfo(), "20", "3")
                    .end("1");
            apiUserRequest.setCarInfo(value);
        }else {
            apiUserRequest.setCarInfo("1");
        }
        // 贷款额度
        String loanAmount = apiUserRequest.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            String value = ApiDictUtils.convertLoanAmount(apiUserRequest.getLoanAmount(),true);
            apiUserRequest.setLoanAmount(value);
        }
        // 贷款期限
        String loanTerm = apiUserRequest.getLoanTerm();
        if (ValidParam.isNotEmpty(loanTerm)) {
            String value = ApiDictUtils.convertLoanAmount(apiUserRequest.getLoanTerm(),true);
            apiUserRequest.setLoanTerm(value);
        }

        // 信用卡
        if (ValidParam.isNotEmpty(apiUserRequest.getCreditLimit())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getCreditLimit(), "0", "1")
                    .when(apiUserRequest.getCreditLimit(), "10", "6")
                    .end("1");
            apiUserRequest.setCreditLimit(value);
        }
        // 保单 0:无保险保单，10:缴纳未满1年，20:缴纳1年以上
        // insurancePolicy 保险保单
        // 1 无保险保单
        // 2 缴纳未满1年
        // 3 缴纳1年以上
        // 4 有保险保单
        if (ValidParam.isNotEmpty(apiUserRequest.getInsurancePolicy())) {
            String value = ChooseEq.create()
                    .when(apiUserRequest.getInsurancePolicy(), "0", "1")
                    .when(apiUserRequest.getInsurancePolicy(), "10", "2")
                    .when(apiUserRequest.getInsurancePolicy(), "20", "3")
                    .end();
            apiUserRequest.setInsurancePolicy(value);
        }
        // 职业身份 200:上班族，300:自由职业，400:企业主，500:个体户，800:公务员，900:其他
        // career 职业
        // 1 上班族
        // 2 自由职业
        // 3 企业主（有营业执照）
        // 4 公务员或事业单位
        // 5 个体户
        String career = apiUserRequest.getCareer();
        if (ValidParam.isNotEmpty(career)) {
            String value = ChooseEq.create()
                    .when(career, "200", "1")
                    .when(career, "300", "2")
                    .when(career, "400", "3")
                    .when(career, "500", "5")
                    .when(career, "800", "4")
                    .when(career, "900", "1")
                    .end("1");
            apiUserRequest.setCareer(value);
        }else {
            apiUserRequest.setCareer("1");
        }

        // 月收入
        String money = apiUserRequest.getMonthlySalary();
        if (ValidParam.isNotEmpty(money)) {
            String value = ApiDictUtils.convertLoanAmount(apiUserRequest.getMonthlySalary(),true);
            apiUserRequest.setMonthlySalary(value);
        }
        // salaryType 工资情况 10:银行卡，20:现金，30:自存
        // salaryPayMethod 收入形式
        // 1 银行代发打卡
        // 2 现金收入
        // 3 个人转账
        String salaryPayMethod = apiUserRequest.getSalaryPayMethod();
        if (ValidParam.isNotEmpty(salaryPayMethod)) {
            String value = ChooseEq.create()
                    .when(salaryPayMethod, "10", "1")
                    .when(salaryPayMethod, "20", "2")
                    .when(salaryPayMethod, "30", "3")
                    .end();
            apiUserRequest.setSalaryPayMethod(value);
        }
        // education 1:大专以下 ,2:大专，3:本科 4:本科以上
        // educationAttainment 学历
        // 1 初中及以下
        // 2 中专
        // 3 高中
        // 4 大专
        // 5 本科
        // 6 研究生及以上
        String educationAttainment = apiUserRequest.getEducationAttainment();
        if (ValidParam.isNotEmpty(educationAttainment)) {
            String value = ChooseEq.create()
                    .when(educationAttainment, "1", "3")
                    .when(educationAttainment, "2", "4")
                    .when(educationAttainment, "3", "5")
                    .when(educationAttainment, "4", "6")
                    .end();
            apiUserRequest.setEducationAttainment(value);
        }
        // 工龄 10:0~6个月，20:6~12个月，30:12个月以上
        String yearsService = apiUserRequest.getYearsService();
        if (ValidParam.isNotEmpty(yearsService)) {
            String value = ChooseEq.create()
                    .when(yearsService, "10", "1")
                    .when(yearsService, "20", "2")
                    .when(yearsService, "30", "3")
                    .end("1");
            apiUserRequest.setYearsService(value);
        }else {
            apiUserRequest.setYearsService("1");
        }
    }

    @Override
    public Object reqPullApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return null;
    }
    @Override
    public boolean respPullApplyNotice(String responseBody) {
        return false;
    }
    @Override
    public Object reqPushApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return null;
    }
    @Override
    public boolean respPushApplyNotice(String responseBody) {
        return false;
    }
}
